<template>
    <div class="chat-right-left-wrap-wrapper flex-column">
        <div class="chat-right-wrap-top">
            <a-space>
                <a-avatar :size="40" :src="props.employee.avatar" v-if="props.employee.avatar" />
                <a-avatar :size="40" v-else>
                    <template #icon><user-outlined /></template>
                </a-avatar>
                <a-typography-text strong>{{ props.employee.name }}</a-typography-text>
            </a-space>
        </div>
        <div class="chat-right-wrap-bottom-tabs">
            <a-space>
                <a-radio-group v-model:value="tabId" @change="handleChangeTab">
                    <a-radio-button value="1">客户</a-radio-button>
                    <a-radio-button value="2">员工</a-radio-button>
                    <a-radio-button value="3">群聊</a-radio-button>
                </a-radio-group>
            </a-space>
        </div>
        <div class="chat-right-wrap-bottom-search">
            <a-input-search v-if="tabId === '1'" v-model:value="queryParams.keyword" placeholder="输入昵称/备注" allow-clear
                enter-button @search="handleReset()" />
            <a-input-search v-if="tabId === '2'" v-model:value="queryParams.keyword" placeholder="输入姓名/手机号" allow-clear
                enter-button @search="handleReset()" />
            <a-input-search v-if="tabId === '3'" v-model:value="queryParams.keyword" placeholder="输入群名" allow-clear
                enter-button @search="handleReset()" />
        </div>

        <div class="chat-right-wrap-bottom flex-1" ref="scrollRef">
            <p>共{{ state.total }}条数据</p>

            <div class="chat-right-wrap-list flex" v-for="(item, index) in list" :key="index" :class="{
                    active: item[selectKey[tabId]] === state.clientId,
                }" @click="handleSelectClient(item)">
                <template v-if="tabId !== '3'">
                    <div class="flex-shrink">
                        <a-avatar :size="45" :src="item.avatar" v-if="item.avatar" />
                        <a-avatar :size="45" v-else>
                            <template #icon><user-outlined /></template>
                        </a-avatar>
                    </div>
                    <div class="flex-1">
                        <div class="chat-right-wrap-list-remark line-1" :title="item.remark">{{ item.remark }}</div>
                        <div class="chat-right-wrap-list-nickname line-1">{{ item.name }}</div>
                        <div v-if="tabId === '2'" class="chat-right-wrap-list-mobile line-1">{{ item.userid }}</div>
                    </div>
                </template>
                <div class="chat-right-wrap-list-nickname line-1" v-else>{{ item.roomname?item.roomname:'群聊' }}</div>
            </div>

            <div class="flex justify-center loading-wrap" v-if="state.loading">
                <loading-outlined />
                数据加载中...
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
    import type { PropType } from 'vue';
import { ref, reactive, watch } from 'vue';
    import { useInfiniteScroll } from '@vueuse/core';
    import { UserOutlined, LoadingOutlined } from '@ant-design/icons-vue';
    import { getButlerOwner, getButlerGroupChat, getButlerInternalStaff } from '@/api/smss/chat';
    import { isNotEmpty } from '@/utils/is';
    import { selectKey } from './common';

    const props = defineProps({
        // 搜索关键字
        keyword: {
            type: String,
            default: '',
        },
        employee: {
            type: Object as PropType<any>,
            default: () => {},
        },
    });

    const emits = defineEmits(['update:select', 'update:tab']);

    const scrollRef = ref<any>(null);
    const list = ref([]);
    const state = reactive<any>({
        current: 1,
        clientId: '',
        loading: false,
        end: false,
        total: 0,
    });

    const tabId = ref('1');
    const method = {
        '1': getButlerOwner,
        '2': getButlerInternalStaff,
        '3': getButlerGroupChat,
    };
    const searchContentKey = {
        '1': 'ownerContent',
        '2': 'staffContent',
        '3': 'groupChatContent',
    };

    const queryParams = ref<any>({
        keyword: '',
    });

    watch(
        () => props.employee,
        (v, oldV) => {
            console.log(v, oldV);

            if (isNotEmpty(v) && oldV?.id !== v?.id) {
                console.log(v, oldV);
                handleReset();
            }
        },
    );

    const { isLoading } = useInfiniteScroll(
        scrollRef,
        (data: any) => {
            // load more
            loadMore();
        },
        {
            distance: 20,
            canLoadMore: () => !state.end && isNotEmpty(props.employee),
        },
    );

    // 异步数据加载
    const fetchData = async current => {
        return new Promise(resolve => {
            method[`${tabId.value}`]({
                current,
                userId: props.employee.workPhone,
                [`${searchContentKey[tabId.value]}`]: queryParams.value.keyword,
            })
                .then(res => {
                    const { records = [], pages, current, total } = res.data;
                    state.total = total;
                    if (pages > current) {
                        state.current++;
                    }
                    state.end = pages === current;
                    resolve(records);
                })
                .catch(err => {
                    console.log(err);
                    resolve([]);
                });
        });
    };

    const loadMore = async () => {
        if (state.loading) return;
        state.loading = true;
        try {
            if (!isNotEmpty(props.employee)) return false;
            if (state.end) return false;
            const newItems: any = await fetchData(state.current);
            list.value.push(...newItems);

            if (isNotEmpty(list.value)) {
                if (isNotEmpty(state.clientId)) {
                    const item = list.value.find(item => item.id === state.employeeId);
                    handleSelectClient(isNotEmpty(item) ? item : list.value[0]);
                } else {
                    handleSelectClient(list.value[0]);
                }
            }
        } catch (error) {
            console.error('加载失败', error);
        } finally {
            state.loading = false;
        }
    };

    const handleReset = () => {
        state.current = 1;
        state.total = 0;
        state.end = false;
        list.value = [];
        state.loading = false;

        loadMore();
    };

    const handleChangeTab = e => {
        tabId.value = e.target.value;
        emits('update:tab', tabId.value);
        handleReset();
    };

    const handleSelectClient = item => {
        state.clientId = item[selectKey[tabId.value]];
        emits('update:select', item);
    };
</script>

<style lang="less" scoped>
.chat-right-left-wrap-wrapper {
    height: 100%;
    background-color: #fff;

    .chat-right-wrap-top {
        padding: 6px 10px 6px 10px;
        border-right: 1px solid #d9d9d9;
    }

    .chat-right-wrap-bottom-tabs,
    .chat-right-wrap-bottom-search {
        padding: 10px;
    }

    .chat-right-wrap-bottom-tabs {
        padding-bottom: 0;
    }

    .chat-right-wrap-bottom {
        overflow-y: auto;
        padding: 10px;

        .chat-right-wrap-list {
            padding: 5px;
            margin-bottom: 5px;
            border-left: 3px solid #fff;
            cursor: pointer;

            &.active,
            &:hover {
                background: #effaff;
                border-left: 3px solid #1c90ff;
            }

            &>.flex-1 {
                margin-left: 10px;

                .chat-right-wrap-list-remark {
                    line-height: 20px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    font-size: 15px;
                }

                .chat-right-wrap-list-nickname {
                    color: #999;
                    font-size: 13px;
                    margin-top: 6px;
                }
                .chat-right-wrap-list-mobile{
                    margin-top: 6px;
                }
            }
        }
    }
}
</style>
